var dataPost = {
   
};

var urlPost = "but/ajax/SanPham.aspx?type=sp";


// Json Get function to retrive data from server

$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
    success: function (data, textStatus, jqXHR) {
        writeLog(data);
    },
    error: function (xhr, status, error) {

    }
});  // End ajax post

var dataList;
var viewModel = new function () {

    this.productList = ko.observableArray();
    this.listByGrid = ko.observable(true);
    
	this.PageSize = ko.observable(6);
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.productList().length / this.PageSize()));
    }, this);
    this.CurrentPageIndex = ko.observable(1);
	this.itemsOnCurrentPage = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
			pagesize = parseInt(pagevalue, 10);

        if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1),
				endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.productList.slice(startIndex, endIndex);
        }
    }, this);
	this.existProduct = ko.computed(function () {
        if(this.productList().length > 0) return true;
		return false;
    }, this);
	
    /////////////////////////////////////// Init data /////////////////////////////////////////////
    var i = 0;
    // Class to represent a row in the table products
    function ProductItem(_Type, _Price, _Vendor, _Warranty, _MadeIn) {
        this.Id = i;
        this.Name = "Sản phẩm " + i;
        this.ImagePath = "images/products/" + i + ".PNG";
        this.Type = _Type;
        this.Price = _Price;
        this.PriceFormat = formatCurrency("#.##0,#", _Price) + " VNĐ";
        this.Vendor = _Vendor;
        this.Warranty = _Warranty;
        this.MadeIn = _MadeIn;
        i++;
    }

    this.productList.push(new ProductItem("ButBi", 6900000, "PARKER", "2", "Italy")); //0
    this.productList.push(new ProductItem("ButDa", 200000, "WATERMAN", "2", "Japan")); //1
    this.productList.push(new ProductItem("ButMay", 2500000, "PARKER", "2", "Italy")); //2
    this.productList.push(new ProductItem("ButBi", 73000000, "PARKER", "2", "Italy")); //3
    this.productList.push(new ProductItem("ButBi", 131100000, "WATERMAN", "2", "Japan")); //4
    this.productList.push(new ProductItem("ButMay", 4500000, "PARKER", "2", "Italy")); //5
    this.productList.push(new ProductItem("ButBi", 500000, "PARKER", "2", "Japan")); //6
    this.productList.push(new ProductItem("ButMay", 9500000, "WATERMAN", "2", "Japan")); //7
    this.productList.push(new ProductItem("ButDa", 10500000, "PARKER", "2", "Italy")); //8
    this.productList.push(new ProductItem("ButDa", 7600000, "WATERMAN", "2", "Japan")); //9
    this.productList.push(new ProductItem("ButMay", 18500000, "PARKER", "2", "Korea")); //10
    this.productList.push(new ProductItem("ButBi", 9500000, "WATERMAN", "2", "Korea")); //11
    this.productList.push(new ProductItem("ButDa", 10000000, "PARKER", "2", "Italy")); //12
    this.productList.push(new ProductItem("ButMay", 54500000, "WATERMAN", "2", "Italy")); //13
    this.productList.push(new ProductItem("ButBi", 21000000, "PARKER", "2", "Korea")); //14
    this.productList.push(new ProductItem("ButMay", 37000000, "PARKER", "2", "Japan")); //15

    //this.productListOrg(this.productList());
    dataList = this.productList();
    this.ProductCount = ko.observable(this.productList().length);
    //writeLog(dataList);

    // Vendor
    function VendorItem(_Name) {
        this.Id = "vendor_" + _Name;
        this.Name = _Name;
        var total = 0;
        ko.utils.arrayForEach(dataList, function (item) {
            if (item.Vendor == _Name) total++;
        });
        this.Count = total;
    }
    this.vendorList = ko.observableArray();
    this.vendorList.push(new VendorItem("PARKER"));
    this.vendorList.push(new VendorItem("WATERMAN"));

    // Product type (but da, but bi, but may)
    function PTypeItem(_Name) {
        this.Id = "type_" + _Name;
        this.Name = _Name;
        this.Label = getLabelByName(_Name);
        var total = 0;
        ko.utils.arrayForEach(dataList, function (item) {
            if (item.Type == _Name) total++;
        });
        this.Count = total;
    }
    this.typeList = ko.observableArray();
    this.typeList.push(new PTypeItem("ButMay"));
    this.typeList.push(new PTypeItem("ButBi"));
    this.typeList.push(new PTypeItem("ButDa"));
    this.typeList.push(new PTypeItem("PhuKien"));

    // MadeIn (Han quoc, Nhat ban)
    function MadeInItem(_Name) {
        this.Id = "madeIn_" + _Name;
        this.Name = _Name;
        this.Label = getCountryByName(_Name);
        var total = 0;
        ko.utils.arrayForEach(dataList, function (item) {
            if (item.MadeIn == _Name) total++;
        });
        this.Count = total;
    }
    this.madeInList = ko.observableArray();
    this.madeInList.push(new MadeInItem("Korea"));
    this.madeInList.push(new MadeInItem("Italy"));
    this.madeInList.push(new MadeInItem("Japan"));

    // Filter in Price min to max 
    function MinMaxItem(_MinP, _MaxP) {
        this.Id = "minMax_" + _MinP + "_" + _MaxP;
        this.MinP = parseInt(_MinP);
        this.MaxP = parseInt(_MaxP);
        this.Label = getMinMaxByLabel(_MinP, _MaxP);
    }
    this.minMaxList = ko.observableArray();
    this.minMaxList.push(new MinMaxItem(1, 0));
    this.minMaxList.push(new MinMaxItem(1, 5));
    this.minMaxList.push(new MinMaxItem(5, 10));
    this.minMaxList.push(new MinMaxItem(10, 20));
    this.minMaxList.push(new MinMaxItem(20, 50));
    this.minMaxList.push(new MinMaxItem(50, 100));
    this.minMaxList.push(new MinMaxItem(0, 100));

	// Properties of dropdownlist
	function OptionItem(_Id, _Name) {
		this.Id = _Id;
		this.Name = _Name;
	}
	this.OrderOptions = ko.observableArray();
	this.OrderOptions.push(new OptionItem("price_asc", "Giá tăng dần"));
	this.OrderOptions.push(new OptionItem("price_desc", "Giá giảm dần"));
	this.OrderOptions.push(new OptionItem("name_asc", "Từ A đến Z"));
	this.OrderOptions.push(new OptionItem("name_desc", "Từ Z đến A"));
	this.selectOrderId = ko.observable();
	
	this.ShowOptions = ko.observableArray();
	this.ShowOptions.push(new OptionItem(6, "6"));
	this.ShowOptions.push(new OptionItem(9, "9"));
	this.ShowOptions.push(new OptionItem(10, "10"));
	this.ShowOptions.push(new OptionItem(15, "15"));
	this.ShowOptions.push(new OptionItem(20, "20"));
	this.ShowOptions.push(new OptionItem(50, "50"));
	this.ShowOptions.push(new OptionItem(75, "75"));
	this.ShowOptions.push(new OptionItem(100, "100"));
	this.selectShowId = ko.observable(6);
	
	this.selectOrderChanged = function(event) {
		sorting();
    }
	this.selectShowChanged = function(event) {
		this.PageSize(this.selectShowId());
		if(viewModel.productList().length > 0)
			this.CurrentPageIndex(1);
		else
			this.CurrentPageIndex(0);
    }
    /////////////////////////////////////// Computed /////////////////////////////////////////////
    this.GetByVendor = function (vendor, event) {
        ProductListCompute("Vendor", vendor.Name);
        SetLinkActivation(vendor.Id);
        
    }

    this.GetByType = function (type, event) {
        ProductListCompute("Type", type.Name);
        SetLinkActivation(type.Id);
  
    }
    this.GetByMadeIn = function (madeIn, event) {
        ProductListCompute("MadeIn", madeIn.Name);
        SetLinkActivation(madeIn.Id);

    }
    this.GetByMinMax = function (minMax, event) {
        ProductListCompute("MinMax", minMax);
        SetLinkActivation(minMax.Id);
        
    }
	// Paginate
    this.PreviousPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn-image btn-prev-arrow prev-active";
        }
        else {
            return "btn-image btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn-image btn-next-arrow next-disabled";
        else
            return "btn-image btn-next-arrow";
    }, this);
	
	// Listing
	this.GridButtonClass = ko.computed(function () {
	    return (this.listByGrid()) ? "btn-image grid-active" : "btn-image grid-non-active";
    }, this);
	this.ListButtonClass = ko.computed(function () {
	    return (this.listByGrid()) ? "btn-image list-non-active" : "btn-image list-active";
    }, this);
};

ko.applyBindings(viewModel, document.getElementById('viewUsers'));

function GetAllItems() {
    ProductListCompute("All", "");
}

function ProductListCompute(filterType, filterBy) {
    if (filterType == "All") {
		RefreshProductList(dataList);
    }
    else {
        //writeLog("filterType:" + filterType);
        var dataFiltered = ko.utils.arrayFilter(dataList, function (item) {
            if (filterType == "Vendor") return item.Vendor == filterBy;
            if (filterType == "Type") return item.Type == filterBy;
            if (filterType == "MadeIn") return item.MadeIn == filterBy;
            if (filterType == "MinMax") {
                //writeLog("MinMax");
                //writeLog(item.Price + ":" + filterBy.MinP);
                if (filterBy.MaxP == 0) return parseFloat(item.Price/1000000) < filterBy.MinP;
                if (filterBy.MinP == 0) return parseFloat(item.Price/1000000) > filterBy.MaxP;
                return (parseFloat(item.Price / 1000000) >= filterBy.MinP && parseFloat(item.Price / 1000000) <= filterBy.MaxP);
            }
        });
		RefreshProductList(dataFiltered);
 
    }
}

function getLabelByName(name) {
    switch (name) {
        case ("ButBi"):
            return "Bút bi";
            break;
        case ("ButMay"):
            return "Bút máy";
            break;
        case ("ButDa"):
            return "Bút dạ";
            break;
        case ("PhuKien"):
            return "Mực & ruột, phụ kiện";
            break;
        default:
            return "Loại khác";
            break;
    }
}

function getCountryByName(name) {
    switch (name) {
        case ("Japan"):
            return "Nhật Bản";
            break;
        case ("Korea"):
            return "Hàn Quốc";
            break;
        case ("Italy"):
            return "Italy";
            break;
    }
}
function getMinMaxByLabel(_MinP, _MaxP) {
    if (_MaxP == 0) return ("Dưới " + _MinP + " triệu");
    if (_MinP == 0) return ("Trên " + _MaxP + " triệu");
    return ("Từ " + _MinP + " triệu - " + _MaxP + " triệu");
}

function SetLinkActivation(linkId) {
    $('#cat-sidebar').find('.link-active').removeClass('link-active');
	$("#" + linkId).addClass("link-active");
}

function ListByGrid() {
    viewModel.listByGrid(true);
}
function ListByList() {
    viewModel.listByGrid(false);
}
function RefreshProductList(data) {
	viewModel.productList(data);
	viewModel.ProductCount(viewModel.productList().length);
	sorting();
	if(viewModel.productList().length > 0)
		viewModel.CurrentPageIndex(1);
	else
		viewModel.CurrentPageIndex(0);
} 
// sort all items
function SortByPropertyName(items, propertyName, sortOrder) {
	return items.sort(sortProperty(propertyName, sortOrder));
}
function sortProperty(property, sortOrder) {
	if (sortOrder == "asc") {
		return function (a, b) {
			if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
				return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
			}
			else {
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) < parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) > parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
				}
			}
		}
	}
	else {
		return function (a, b) {
			
			if ($.isNumeric(a[property]) && $.isNumeric(b[property])) {
				return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
			}
			else {
				if (isDateTime(a[property]) && isDateTime(b[property])) {
					return (parseDateTime(a[property]) > parseDateTime(b[property])) ? -1 : (parseDateTime(a[property]) < parseDateTime(b[property])) ? 1 : 0;
				} else {
					return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
				}
			}

		}
	}
}
function sorting() {
	writeLog(viewModel.selectOrderId());
	if (viewModel.selectOrderId() == undefined) return;
	if (viewModel.selectOrderId() == "price_asc") viewModel.productList(SortByPropertyName(ko.utils.unwrapObservable(viewModel.productList()), 'Price', 'asc'));
	if (viewModel.selectOrderId() == "price_desc") viewModel.productList(SortByPropertyName(ko.utils.unwrapObservable(viewModel.productList()), 'Price', 'desc'));
	if (viewModel.selectOrderId() == "name_asc") viewModel.productList(SortByPropertyName(ko.utils.unwrapObservable(viewModel.productList()), 'Name', 'asc'));
	if (viewModel.selectOrderId() == "name_desc") viewModel.productList(SortByPropertyName(ko.utils.unwrapObservable(viewModel.productList()), 'Name', 'desc'));
}